// pages/login/index.js
const app = getApp().globalData //获取并设置tabbar
import {
  request,
  logIn,
  getLocation,
  setRouter
} from '../../utils/requestUtils';
Page({
  data: {
    form: {
      username: '',
      password: 'xC9iM9y9jDba8'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //getApp().routerGuard.beforeEach(this, options);
  },
  

  //页面加载
  onShow(){
    //获取token；获取
    const token =  wx.getStorageSync('token');
    const postCode =  wx.getStorageSync('postCode')
    if(token && postCode){
      this.getInfo()
    }

    console.log("测试")
  },
  //用户登录
  async submit_btn() {
    let usernameCheck = this.checkFn('username', 'usernameErr', '账号不能为空')
    let passwordCheck = this.checkFn('password', 'passwordErr', '密码不能为空')
    if (usernameCheck && passwordCheck) {
      const result = await logIn({
        url: '/login',
        method: "POST",
        data: {
          username: this.data.form['username'],
          password: this.data.form['password'],
        }
      });
      console.log('result', result)
      if (result.data.code == 200) {
        wx.setStorage('menus', result.data.menus)
        this.getInfo()
      }
    } else {
      console.log("222")
    }
  },
  // 获取用户信息放入缓存中
  async getInfo() {
    const result = await request({
      url: `/getInfo`,
      method: "GET"
    })
    console.log('menus', wx.getStorage('menus'))
    wx.setStorageSync('user', result.data.user)
    wx.setStorageSync('roles', result.data.roles)
    wx.reLaunch({
      url:wx.getStorageSync('menus')[0].path,
    })
  },
  // checkFn方法表单验证
  checkFn(err, errKey, errStr) {
    console.log('this.data.form[err]', this.data.form[err])
    if (!this.data.form[err].trim()) {
      this.setData({
        [errKey]: errStr
      })
      return false
    } else {
      this.setData({
        [errKey]: ''
      })
      return true
    }
  },
  //设置菜单

  // 输入框方法
  onChange(event) {
    console.log('event.currentTarget.dataset["input"]', event.currentTarget.dataset['input'])
    switch (event.currentTarget.dataset['input']) {
      case 'username':
        this.setData({
          "form.username": event.detail,
        })
        break;
      case 'password':
        this.setData({
          "form.password": event.detail,
        })
        break;
    }
  },
  //获取当前位置
  async getLocationHander() {
    const result = await getLocation()
    //登录成功后获取当前用户位置
    const location = {
      latitude: result.latitude,
      longitude: result.longitude
    }
    wx.setStorageSync('location', location)
  },
})
